import React, { useEffect, useMemo, useState } from 'react'
import style from './Note.module.less'
import { Alert, Button, Form, List, Modal, Space, Input, message } from 'antd'
import { awaitWrap, confirmAction, formatDate } from '@js/tool'
import { $get, $post, $put } from '@js/authRequest'
import classNames from 'classnames'
import { FormOutlined, DeleteOutlined, PlusOutlined } from '@ant-design/icons'
import { useUid } from '@hooks/userInfo'

const { TextArea } = Input
const { Item, useForm } = Form

async function deleteRequest (id) {
  const res = await $put(`/api/xapc/casenote/${id}`, { status: 0 })
  if (res.status !== 1) {
    throw new Error(res.message)
  }
  return res.data
}

async function delHandle (id, callback) {
  const h = message.loading('删除中', 120)
  const [e] = await awaitWrap(deleteRequest(id))
  h()
  if (e === null) {
    message.success('删除成功', 1)
    callback()
  }
}

async function addRequest (caseid, content) {
  const res = await $post('/api/xapc/casenote', { caseid, content })
  if (res.status !== 1) {
    throw new Error(res.message)
  }
  return res.data
}

async function updateRequest (id, content) {
  const res = await $put(`/api/xapc/casenote/${id}`, { content })
  if (res.status !== 1) {
    throw new Error(res.message)
  }
  return res.data
}

async function submitHandle (caseid, editData, content, callback) {
  const h = message.loading('提交中', 120)
  const fn = editData ? updateRequest : addRequest
  const [e] = await awaitWrap(fn(editData ? editData.id : caseid, content))
  h()
  if (e === null) {
    callback()
  }
}

async function getListRequest (caseid) {
  const res = await $get('/api/xapc/casenote', { params: { caseid } })
  if (res.status !== 1) {
    throw new Error(res.message)
  }
  res.data.sort((a, b) => {
    if (a.update_datetime && b.update_datetime) {
      return a.update_datetime - b.update_datetime
    }
    return a.create_datetime - b.create_datetime
  })
  return res.data
}

async function initList (caseid, setList, setLoading) {
  setLoading(true)
  const [e, d] = await awaitWrap(getListRequest(caseid))
  setLoading(false)
  if (e === null && d !== null) {
    setList(d)
  }
}

function Main ({ caseDetail, refreshFn }) {
  const [loading, setLoading] = useState(false)
  const [list, setList] = useState([])
  const [visible, setVisible] = useState(false)
  const [formRef] = useForm()
  const [formVisible, setFormVisible] = useState(false)
  const [modifyData, setModifyData] = useState(null)
  const [version, setVersion] = useState(Date.now())
  const uid = useUid()
  const d = useMemo(() => {
    if (list.length) {
      return list[list.length - 1]
    }
    return undefined
  }, [list])
  useEffect(() => {
    if (caseDetail && caseDetail.note) {
      initList(caseDetail.id, setList, setLoading)
    }
  }, [caseDetail, version])
  useEffect(() => {
    if (formVisible && modifyData && formRef) {
      formRef.setFieldsValue(modifyData)
    } else if (!formVisible && formRef) {
      formRef.resetFields()
    }
  }, [modifyData, formVisible, formRef])
  useEffect(() => {
    if (!visible && formRef) {
      setFormVisible(false)
      setModifyData(null)
      formRef.resetFields()
    }
  }, [visible, formRef])
  return (
    <div className={classNames(style.container, { [style.hide]: !d })}>
      <Modal title={<Space size='middle'><span>便签</span><Button type='primary' size='small' icon={<PlusOutlined />} onClick={() => { setFormVisible(true) }} /></Space>} width={1200} visible={visible} onCancel={() => setVisible(false)} maskClosable={false} footer={null} forceRender>
        <div className={style.modal}>
          <div className={style.left}>
            <div className={style['left-inner']}>
              <List
                dataSource={list} loading={loading} renderItem={(data) => {
                  const editable = data.operatorid === uid
                  return (
                    <div className={classNames(style.item, { [style.active]: data === modifyData })}>
                      <div className={style['item-title']}>
                        <Space size='small'>
                          <span>{data.operator}</span>
                          <span className={style['item-date']}>{formatDate(d.update_datetime || d.create_datetime, 'YYYY-MM-DD HH:mm')}</span>
                        </Space>
                        {
                          editable && (
                            <Space size='small'>
                              <a className={style.btn} onClick={() => { setModifyData(data); setFormVisible(true) }}><FormOutlined /></a>
                              <a className={style.del} onClick={() => { confirmAction('您确定要删除该便签吗？', () => { delHandle(data.id, () => { setVersion(Date.now()) }) }) }}><DeleteOutlined /></a>
                            </Space>
                          )
                        }
                      </div>
                      <div>{data.content}</div>
                    </div>
                  )
                }}
              />
            </div>
          </div>
          <div className={classNames(style.right, { [style['right-hide']]: !formVisible })}>
            <div className={style['form-title']}>{modifyData ? '编辑便签' : '添加便签'}</div>
            <Form form={formRef} onFinish={d => submitHandle(caseDetail.id, modifyData, d.content, () => { setVersion(Date.now()); setFormVisible(false); setModifyData(null) })}>
              <Item noStyle name='id'><span /></Item>
              <Item title=' ' colon={false} name='content'>
                <TextArea placeholder='请输入' autoSize={{ minRows: 18, maxRows: 18 }} />
              </Item>
              <Item title=' ' colon={false} className={style['form-btns']}>
                <Space>
                  <Button onClick={() => { setFormVisible(false); setModifyData(null) }}>取消</Button>
                  <Button type='primary' htmlType='submit'>{modifyData ? '确定' : '添加'}</Button>
                </Space>
              </Item>
            </Form>
          </div>
        </div>
      </Modal>
      {d && <Alert className={style.alert} size='small' showIcon message={<div><div>{d.operator} <span className={style.date}>{formatDate(d.update_datetime || d.create_datetime, 'YYYY-MM-DD HH:mm')}</span></div><div>{d.content}</div></div>} action={[<Button size='small' type='primary' key={0} onClick={() => setVisible(true)}>更多</Button>]} />}
    </div>
  )
}

export default Main
